package oaSystem.web.controller.rest;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import oaSystem.Exception.BizException;
import oaSystem.Exception.BizRunException;
import oaSystem.biz.ActivityBiz;
import oaSystem.biz.EventBiz;
import oaSystem.biz.EventDetailsBiz;
import oaSystem.entity.Activity;
import oaSystem.entity.Employee;
import oaSystem.entity.Event;
import oaSystem.entity.EventDetails;
import oaSystem.entity.JsonResult;
import oaSystem.web.security.Authorize;

@Controller
@RequestMapping("/rest/event")
@RestController
public class Rest_EventController {
	@Autowired
	private EventBiz eventBiz;
	@Autowired
	private EventDetailsBiz eventDetailsBiz;
	@Autowired
	private ActivityBiz activityBiz;
	
	/**
	 * 获取用户的全部活动信息
	 * @return
	 */
	@Authorize(rules="calendar-mine")
	@RequestMapping(value="",method=RequestMethod.GET)
	public List<Event> getInfo(HttpServletRequest request){
		Employee employee=(Employee)request.getSession().getAttribute("user");
		List<Event> list = eventBiz.findEventByEmployeeId(employee.getId());
		return list;
	}
	
	/**
	 * 增加事件
	 * @param request
	 * @param eventDetails
	 * @return
	 */
	@Authorize(rules="calendar-event-add")
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public JsonResult addEvent(HttpServletRequest request,EventDetails eventDetails){
		Employee employee=(Employee)request.getSession().getAttribute("user");
//		Employee employee = new Employee(5);
		EventDetails details = (EventDetails)request.getSession().getAttribute("eventDetails");
		if(details!=null&&details.getActorList()!=null&&details.getActorList().size()>0){
			List<Employee> actorList = details.getActorList();
			eventDetails.setActorList(actorList);
		}
		try {
			eventDetailsBiz.addEventDetails(eventDetails, employee);
		} catch (ParseException e) {
			return new JsonResult(false, "日期格式有误");
		}
		request.getSession().removeAttribute("eventDetails");
		return new JsonResult(true, null);
	}
	
	/**
	 * 临时保存，移除参与者
	 * @param request
	 * @param flag
	 * @param actorId
	 * @return
	 */
	@Authorize(rules="calendar-mine")
	@RequestMapping(value="/{flag}",method=RequestMethod.GET)
	public JsonResult insertActor(HttpServletRequest request,@PathVariable Boolean flag,Integer actorId){
		EventDetails eventDetails = checkEventDetailsAndActorListStatus((EventDetails)request.getSession().getAttribute("eventDetails"));
		List<Employee> actorList=eventDetails.getActorList();
		
		if(actorId==null){
			return new JsonResult(false,"请选择参与者");
		}
		
		Employee actor=checkActor(actorList, actorId);
		try{
			addOrDeleteActor(actorList,actor,flag,actorId);
		}catch(BizRunException e){
			return new JsonResult(false, e.getMessage());
		}
		eventDetails.setActorList(actorList);
		request.getSession().setAttribute("eventDetails", eventDetails);
		
		return new JsonResult(true, null);
	}
	
	/**
	 * 更新活动
	 * @param eventDetails
	 * @param request
	 * @return
	 */
	@Authorize(rules="calendar-event-edit")
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public JsonResult updateEvent(EventDetails eventDetails,HttpServletRequest request){
		Employee employee=(Employee)request.getSession().getAttribute("user");
//		Employee employee = new Employee(5);
		EventDetails details = (EventDetails)request.getSession().getAttribute("eventDetails");
		if(details!=null&&details.getActorList()!=null&&details.getActorList().size()>0){
			List<Employee> actorList = details.getActorList();
			eventDetails.setActorList(actorList);
		}
		try {
			eventDetailsBiz.updateEventDetails(eventDetails, employee, true);
		} catch (ParseException e) {
			return new JsonResult(false, "日期格式有误");
		} catch (BizException e) {
			return new JsonResult(false, e.getMessage());
		}
		request.getSession().removeAttribute("eventDetails");
		return new JsonResult(true, null);
		
		
		/*Employee employee=(Employee)request.getSession().getAttribute("user");
		EventDetails actorList = checkEventDetailsAndActorListStatus((EventDetails)request.getSession().getAttribute("eventDetails"));
		
		
		
		
//		Employee employee = new Employee(5);
		Event event = eventDetails.getEvent();
		if(event==null){
			return new JsonResult(false, "无法获取活动信息");
		}
		try {
			eventBiz.updateActivity(event, employee,true);
			return new JsonResult(true, null);
		} catch (ParseException e) {
			return new JsonResult(false, "日期格式有误");
		} catch (BizException e) {
			return new JsonResult(false, e.getMessage());
		}*/
		
	}
	
	/**
	 * 拖拽修改
	 * @param id
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@Authorize(rules="calendar-event-dropedit")
	@RequestMapping(value="/updatedrop",method=RequestMethod.POST)
	public JsonResult updateDropEvent(EventDetails eventDetails,HttpServletRequest request){
		Employee employee=(Employee)request.getSession().getAttribute("user");
//		Employee employee = new Employee(5);
		Event event = eventDetails.getEvent();
		if(event==null){
			return new JsonResult(false, "无法获取活动信息");
		}
		try {
			eventBiz.updateActivity(event, employee,false);
			return new JsonResult(true, null);
		} catch (ParseException e) {
			return new JsonResult(false, "日期格式有误");
		} catch (BizException e) {
			return new JsonResult(false, e.getMessage());
		}
	}
	
	/**
	 * 删除事件
	 * @param eventId
	 * @param request
	 * @return
	 */
	@Authorize(rules="calendar-delete")
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public JsonResult deleteEvent(Integer eventId,HttpServletRequest request){
		Employee employee=(Employee)request.getSession().getAttribute("user");
//		Employee employee = new Employee(5);
		try {
			eventBiz.deleteActivity(eventId, employee);
		} catch (BizException e) {
			return new JsonResult(false, e.getMessage());
		}
		return new JsonResult(true, null);
	}
	/**
	 * 查询活动（By activityId）
	 * @return
	 */
	@Authorize(rules="calendar-search")
	@RequestMapping(value="/info/{activityId}",method=RequestMethod.GET)
	public Map<String, Object> fetchEventDetails(@PathVariable Integer activityId,HttpServletRequest request){
		Employee employee=(Employee)request.getSession().getAttribute("user");
//		Employee employee = new Employee(5);
		Map<String, Object> map = new HashMap<String, Object>();
		EventDetails eventDetails = eventDetailsBiz.fetchEventDetailsByActivityId(activityId);
		map.put("eventDetails", eventDetails);
		
		Activity activity = activityBiz.fetchActivityById(activityId);
		
		JsonResult jsonResult = eventBiz.checkUserIsMatch(employee, activity);
		map.put("jsonResult", jsonResult);
		return map;
	}
	
	/**
	 * 方法抽取（增加/移除参与者）
	 * @param actorList
	 * @param actor
	 * @param flag
	 * @param actorId
	 * @throws BizRunException
	 */
	private void addOrDeleteActor(List<Employee> actorList, Employee actor, Boolean flag, Integer actorId) throws BizRunException {
		if(flag){
			//增加
			if(actor!=null){
				throw new BizRunException("此参与者已增加");
			}
			actor=new Employee();
			actor.setId(actorId);
			actorList.add(actor);
		}else{
			//移除
			if(actor==null){
				throw new BizRunException("请选择需要移除的参与者");
			}
			actorList.remove(actor);
		}
		
	}

	/**
	 * 方法抽取（检查EventDetails和ActorList是否已被创建）
	 * @param eventDetails
	 * @param actorList
	 */
	private EventDetails checkEventDetailsAndActorListStatus(EventDetails eventDetails) {
		if(eventDetails==null){
			eventDetails=new EventDetails();
		}
		if(eventDetails.getActorList()==null){
			eventDetails.setActorList(new ArrayList<Employee>());
		}
		return eventDetails;
	}

	/**
	 * 方法抽取（检测actor是否存在）
	 * @param eventDetails
	 * @param actorId
	 * @return
	 */
	private Employee checkActor(List<Employee> actorList,Integer actorId){
		if(actorList!=null&&actorList.size()>0){
			for (Employee employee : actorList) {
				if(employee.getId()==actorId){
					return employee;
				}
			}
		}
		return null;
	}
	
	
}
